/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainListFrame.java
 *
 * Created on 2011-10-11, 16:54:01
 */
package com.lanchat.view;

import com.lanchat.model.data.ChatMessage;
import com.lanchat.model.data.User;
import com.lanchat.model.net.NetConstant;
import com.lanchat.model.net.UdpRecv;
import com.lanchat.model.net.UdpSend;
import com.lanchat.model.util.LocalIPGetter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.interfaces.DSAKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class MainListFrame extends javax.swing.JFrame {
    public static HashMap<String,ChatFrame> chatList;
    public static HashMap<String,FileSendFrame> fileSend;
    public static HashMap<String,FileRecvFrame> fileRecv;
    private Thread messageRecv,broadRecv;
    private UdpRecv recv;
    public static  UdpSend send;
    private Timer t;
    public static  User localUser;
    private String bip;
    private String selected="";
    private int filePort;
    ArrayList<String> userList;
    private DatagramSocket ds;

    /** Creates new form MainListFrame */
    public MainListFrame() {        
        initComponents();
        setVisible(true);
        MainListFrame.chatList=new HashMap<String, ChatFrame>();
        MainListFrame.fileRecv=new HashMap<String, FileRecvFrame>();
        MainListFrame.fileSend=new HashMap<String, FileSendFrame>();
        filePort=NetConstant.UDPFILEPORT;
        userList=new ArrayList<String>();
        recv=new UdpRecv();
        send = new UdpSend();
        DefaultListModel m=new DefaultListModel();
        OnlineList.setModel(m);
        SingleButton.setEnabled(false);
        BroadButton.setEnabled(false);
        FileButton.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userName = new javax.swing.JTextField();
        LoginButton = new javax.swing.JButton();
        ExitButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        SingleButton = new javax.swing.JButton();
        BroadButton = new javax.swing.JButton();
        FileButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        OnlineList = new javax.swing.JList();
        RecordButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        userName.setText("自命名");

        LoginButton.setText("LOGIN");
        LoginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginButtonActionPerformed(evt);
            }
        });

        ExitButton.setText("EXIT");
        ExitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("用户名：");

        SingleButton.setText("密聊");
        SingleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SingleButtonActionPerformed(evt);
            }
        });

        BroadButton.setText("群发");
        BroadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BroadButtonActionPerformed(evt);
            }
        });

        FileButton.setText("文件传输");
        FileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FileButtonActionPerformed(evt);
            }
        });

        OnlineList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        OnlineList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                OnlineListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(OnlineList);

        RecordButton.setText("通信记录");
        RecordButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RecordButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(SingleButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(BroadButton)
                            .addGap(8, 8, 8))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGap(10, 10, 10)
                                    .addComponent(LoginButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(ExitButton))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(userName, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(FileButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(RecordButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ExitButton)
                    .addComponent(LoginButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SingleButton)
                    .addComponent(BroadButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FileButton)
                    .addComponent(RecordButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void SingleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SingleButtonActionPerformed
        // TODO add your handling code here:
        if(selected == null ? "" == null : selected.equals("")){
            JOptionPane.showMessageDialog(null, "请选择聊天对象！");
            return;
        }
        new ChatFrame(localUser, selected);
    }//GEN-LAST:event_SingleButtonActionPerformed

    private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
        // TODO add your handling code here:
        String uName=userName.getText();
        if(uName == null ? "" == null : uName.equals("")){
            JOptionPane.showMessageDialog(null, "用户名不能为空");
            return;
        }
        localUser=new User();        
        localUser.setAddress(LocalIPGetter.getMyIP());
        localUser.setUserName(uName);
        messageRecv=new Thread(new Runnable() {
            @Override
            public void run() {
                
                while(true){
                    try {
                        ChatMessage msg=(ChatMessage)recv.run();
                        switch(msg.getType()){
                        case ChatMessage.LOGIN:
                            if((!(userList.contains(msg.getIP())))&&(!msg.getIP().equals(localUser.getAddress()))){
                                userList.add(msg.getIP());
                                DefaultListModel model=(DefaultListModel)OnlineList.getModel();
                                String add=msg.getUser()+":"+msg.getIP();
                                model.addElement(add);
                                ChatMessage res=new ChatMessage("login", localUser.getUserName(),
                                    localUser.getAddress(), ChatMessage.LOGIN);
                                send.send(res,msg.getIP());
                                System.out.print(msg.getIP());
                            }
                            break;
                        case ChatMessage.LOGOUT:
                            if(!(localUser.getAddress().equals(msg.getIP()))){
                                userList.remove(msg.getIP());
                                DefaultListModel model=(DefaultListModel)OnlineList.getModel();
                                model.removeElement(msg.getUser()+":"+msg.getIP());
                                //System.out.print(msg.getIP());
                            }
                            break;
                        case ChatMessage.MSG:
                            if(MainListFrame.chatList.containsKey(msg.getIP())){
                                ((ChatFrame)(MainListFrame.chatList.get(msg.getIP()))).AddMessage(msg);
                            }
                            else{
                                new ChatFrame(localUser, msg.getUser()+":"+msg.getIP());
                                ((ChatFrame)(MainListFrame.chatList.get(msg.getIP()))).AddMessage(msg);
                            }
                            break;
                        case ChatMessage.FILE_SEND:
                            String fname=msg.getMsg().substring(0, msg.getMsg().indexOf('#'));
                            int result=JOptionPane.showConfirmDialog(null, "收到来自"+msg.getIP()+":"+msg.getUser()+"的文件发送请求："+fname,
                                    "收到文件发送请求",JOptionPane.YES_NO_OPTION);
                            if(result==JOptionPane.YES_OPTION){
                                ChatMessage cmAgree=new ChatMessage("Agree#"+filePort, localUser.getUserName(),
                                        localUser.getAddress(), ChatMessage.FILE_RECV);
                                send.send(cmAgree, msg.getIP());
                                FileRecvFrame frframe=new FileRecvFrame(msg.getMsg(), filePort);
                                filePort++;
                            } else if(result==JOptionPane.NO_OPTION){
                                ChatMessage cmDisagree=new ChatMessage("Disagree", localUser.getUserName(), localUser.getAddress(), ChatMessage.FILE_RECV);
                                MainListFrame.send.send(cmDisagree, msg.getIP());
                            }
                            break;
                        case ChatMessage.FILE_RECV:
                            if(msg.getMsg().startsWith("Agree")){
                                String[] tmp=msg.getMsg().split("#");
                                FileSendFrame fsw=MainListFrame.fileSend.get(msg.getIP());
                                fsw.SetPort(Integer.parseInt(tmp[1]));
                                Thread t=new Thread(fsw);
                                t.start();
                            }else if(msg.getMsg().startsWith("Disagree")){
                                FileSendFrame fsw=MainListFrame.fileSend.get(msg.getIP());
                                JOptionPane.showMessageDialog(null, "对方拒绝了发送请求！");
                                fsw.dispose();
                            }
                        case ChatMessage.NULL:
                            break;
                    }
                    } catch (Exception ex) {
                        Logger.getLogger(MainListFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }
            }
        });
        messageRecv.start();
        String ip;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
            System.out.print(ip);
            String preip=ip.substring(0,ip.lastIndexOf('.')+1);
            bip=preip+255;
           
            ChatMessage login=new ChatMessage("login", localUser.getUserName(),
                    localUser.getAddress(), ChatMessage.LOGIN);
            
            send.send(login, bip);
            
           
        } catch (UnknownHostException ex) {
            Logger.getLogger(MainListFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        LoginButton.setEnabled(false);
        SingleButton.setEnabled(true);
        BroadButton.setEnabled(true);
        FileButton.setEnabled(true);
    }//GEN-LAST:event_LoginButtonActionPerformed

    private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitButtonActionPerformed
        // TODO add your handling code here:
        if(!(LoginButton.isEnabled())){
            ChatMessage logout=new ChatMessage("logout", localUser.getUserName(),
                    localUser.getAddress(), ChatMessage.LOGOUT);
            send.send(logout, bip);
        }
        this.dispose();
        System.exit(0);
    }//GEN-LAST:event_ExitButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if(!(LoginButton.isEnabled())){
            ChatMessage logout=new ChatMessage("logout", localUser.getUserName(),
                    localUser.getAddress(), ChatMessage.LOGOUT);
            send.send(logout, bip);           
        }
    }//GEN-LAST:event_formWindowClosing

    private void OnlineListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_OnlineListValueChanged
        // TODO add your handling code here:
        selected=(String)OnlineList.getSelectedValue();
        //selected=selected.substring(0, selected.length()/2);
        System.out.print(selected);
    }//GEN-LAST:event_OnlineListValueChanged

    private void RecordButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecordButtonActionPerformed
        // TODO add your handling code here:
        new RecordFrame();
    }//GEN-LAST:event_RecordButtonActionPerformed

    private void BroadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BroadButtonActionPerformed
        // TODO add your handling code here:
        LinkedList<String> list=new LinkedList<String>();
        DefaultListModel model=(DefaultListModel)OnlineList.getModel();
        System.out.println("\n"+model.size());
        for(int i=0;i<model.size();i++){
            String tmp=(String)model.get(i);
            list.add(tmp);
        }
        new BroadFrame(list);
    }//GEN-LAST:event_BroadButtonActionPerformed

    private void FileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FileButtonActionPerformed
        // TODO add your handling code here:
        if(selected == null ? "" == null : selected.equals("")){
            JOptionPane.showMessageDialog(null, "请选择发送对象！");
            return;
        }
        JFileChooser jfc=new JFileChooser();
        jfc.setDialogTitle("请选择文件");
        jfc.setMultiSelectionEnabled(false);
        if(JFileChooser.APPROVE_OPTION==jfc.showOpenDialog(null)){
            File f=jfc.getSelectedFile();
            String IP=selected.substring(selected.indexOf(':')+1);
            new FileSendFrame(IP, f);
        }
    }//GEN-LAST:event_FileButtonActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BroadButton;
    private javax.swing.JButton ExitButton;
    private javax.swing.JButton FileButton;
    private javax.swing.JButton LoginButton;
    private javax.swing.JList OnlineList;
    private javax.swing.JButton RecordButton;
    private javax.swing.JButton SingleButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField userName;
    // End of variables declaration//GEN-END:variables
}
